console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';

let baseInfoCache;
let taxInfo = {
  institution: 2007, // 默认2013
  nsrsbh: '', // 纳税人申报号
  nsrmc: '', // 纳税人名称（纳税公司）
  skssqq: '', // 税款所属期起
  skssqz: ''// 税款所属期止
};

$(window).ready(function () {
  // 登录填写账号密码
  if (/\/cas\/login/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }

  // 小企业会计准则
  if (/\/sb\/wssb\/menu\/sbtree/g.test(window.location.pathname)) {
    $('html').on('click', '.mini-tab', function () {
      let index = $(this).attr('index');
      let tableTitle = $('.table-title').eq(index).text(),
        taxType = getTaxType('', tableTitle);

      // 获取申报周期，填充数据
      let period = getReportingCycle();

      // 渲染填报时间，填报周期
      sendFilter(period, taxType);
    });

    taxInfo.institution = 2007;
  }
});

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    data = data.data;
    let sheet = data.saasData.sheet;
    if (sheet == 'sds' || sheet == 'zzs') {
      fillInput(data, sheet);
    } else {
      fillInput(await transformDataByOpenWeb(data));
    }
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    autoInputAccount(baseInfoCache);
  }
}, false);
/**
 * 获取公司信息
 */
function getNationData() {
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  $('#username').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  $('#password').val(companyInfo.nationalTaxPass);
}

function fillInput({ saasData, baseInfo }) {
  let sheet = saasData.sheet;
  let message = '填报成功';
  try {
    let inputData = saasData.data;
    if (sheet === 'sds') {
      inputData = delSdsData(inputData.openParams.inputData.data.profit, baseInfo.companyInfo.institutionCode);
    }
    let iframeWindow = $('#printIframe').contents().find('iframe')[0].contentWindow.document.getElementsByTagName('iframe')[0].contentWindow;
    for (let key in inputData) {
      let domKey = iframeWindow.document.getElementById(`${key}`);
      if (domKey) {
        domKey.click();
        let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
        let domInput = iframeWindow.document.getElementsByTagName('input')[0];
        // while(!domInput){
        //   sleep(10);
        // }
        if (domInput) {
          domInput.value = value;
        }
      }
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}


function delSdsData(profitData, institutionCode) {
  let sdsData = {};
  if (institutionCode == 1) {
    sdsData = {
      '001_8_5': profitData.SQJE_1_1,
      '001_9_5': profitData.SQJE_1_2,
      '001_10_5': profitData.SQJE_1_15
    };
  } else {
    sdsData = {
      '001_8_5': profitData.BNLJJE_1,
      '001_9_5': profitData.BNLJJE_2,
      '001_10_5': profitData.BNLJJE_30
    };
  }

  return sdsData;
}


/**
 * 获取 税类型 用于填充填报类型 '增值税一般纳税人'
 * @returns {taxType}
 */
function getTaxType(taxTypeStr, title) {
  taxTypeStr = taxTypeStr || '增值税一般纳税人';
  let taxType = null;

  if (!title) {
    if (taxTypeStr.search('增值税') != -1) {
      taxType = 'zzs';
    } else if (taxTypeStr.search('所得税') != -1) {
      taxType = 'sds';
    } else if (taxTypeStr.search('财务报表') != -1) {
      taxType = 'balance';
    }
  } else if (title.search('资产负债表') != -1) {
    taxType = 'balance';
  } else if (title.search('利润表') != -1) {
    taxType = 'profit';
  } else if (title.search('现金流量表') != -1) {
    taxType = 'cash';
  } else {
    taxType = 'balance';
  }
  return taxType;
}

/**
 * @param timeStr 时间字符串 2017-04-01~2017-06-30
 * 获取申报周期并且填充数据
 */
function getReportingCycle() {
  let sssq_q = $('.sssqq').eq(0).text().substr(0, 7);
  let sssq_z = $('.sssqz').eq(0).text().substr(0, 7);
  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z
  };
}


function sendFilter(period, taxType) {
  let sssq_q = period.sssq_q,
    sssq_z = period.sssq_z;

  if (sssq_q && sssq_z) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType,
        startTime: sssq_q,
        endTime: sssq_z
      }
    }, '*');
  } else if (taxType) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType
      }
    }, '*');
  }
}

/**
 * 同步延时
 * @param numberMillis
 */
function sleep(numberMillis) {
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while (true) {
    now = new Date();
    if (now.getTime() > exitTime) { return; }
  }
}
